<?php
declare (strict_types=1);

namespace app\admin\service\iot;

use app\admin\model\iot\Device;
use app\admin\model\iot\DeviceLog;
use app\BaseService;
use iot\DeviceClient;
use think\response\Json;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 设备管理服务层
 */
class DeviceService extends BaseService
{
    /**
     * 获取所有设备类型
     * @return Json
     */
    public function deviceTypeAll(): Json
    {
        $types = Device::$deviceTypeArr;
        return jsonReturn(1, $types);
    }

    /**
     * 终端仓库列表
     * @param array $params
     * @return Json
     */
    public function warehouseList(array $params): Json
    {
        $where[] = ['install', '<>', 1];
        $where[] = ['closed', '=', 0];
        //搜索imei
        if ($params['imei']) {
            $where[] = ['imei', 'like', '%' . $params['imei'] . '%'];
        }
        //搜索mac_id
        if ($params['mac_id']) {
            $where[] = ['mac_id', '=', $params['mac_id']];
        }
        //搜索apk版本号
        if ($params['apk']) {
            $where[] = ['apk', '=', $params['apk']];
        }
        //搜索设备
        if (!is_null($params['install'])) {
            $where[] = ['install', '=', $params['install']];
        }
        //创建时间筛选
        if ($params['start_time'] && $params['end_time']) {
            $start_time = (int)$params['start_time'];
            $end_time = (int)$params['end_time'];
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        //获取列表
        $field = 'id,imei,mac_id,type,apk,firmware,install,online,create_time';
        $data = Device::getList($where, $params['page'], $params['limit'], 'id desc', $field);
        return jsonReturn(1, $data);
    }

    /**
     * 设备列表
     * @param array $params
     * @return Json
     */
    public function deviceList(array $params): Json
    {
        $where[] = ['install', '=', 1];
        $where[] = ['closed', '=', 0];
        //搜索imei
        if ($params['imei']) {
            $where[] = ['imei', 'like', '%' . $params['imei'] . '%'];
        }
        //搜索类型
        if ($params['type']) {
            $where[] = ['type', '=', $params['type']];
        }
        if ($params['mac_id']) {
            $where[] = ['mac_id', '=', $params['mac_id']];
        }
        //创建时间筛选
        if ($params['start_time'] && $params['end_time']) {
            $start_time = (int)$params['start_time'];
            $end_time = (int)$params['end_time'];
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        //获取列表
        $data = Device::getList($where, $params['page'], $params['limit'], 'id desc');
        return jsonReturn(1, $data);
    }

    public function deviceListExport(array $params): Json
    {
        $where[] = ['install', '=', 1];
        $where[] = ['closed', '=', 0];
        //搜索imei
        if ($params['imei']) {
            $where[] = ['imei', 'like', '%' . $params['imei'] . '%'];
        }
        //搜索类型
        if ($params['type']) {
            $where[] = ['type', '=', $params['type']];
        }
        if ($params['mac_id']) {
            $where[] = ['mac_id', '=', $params['mac_id']];
        }
        //创建时间筛选
        if ($params['start_time'] && $params['end_time']) {
            $start_time = (int)$params['start_time'];
            $end_time = (int)$params['end_time'];
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        //获取列表
        $list = Device::getList($where, 1, 10000, 'id desc');
        //导出
        $title = ['IMEI', '设备号','在线状态','APK版本号','安装时间','最后通讯时间'];
        // Create new Spreadsheet object
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $spreadsheet->getActiveSheet()->getColumnDimension($titCol)->setAutoSize(true);
            $titCol++;
        }
        $row = 2; // 从第二行开始
        if($list['data']){
            foreach ($list['data'] as $item) {
                $dataCol = 'A';
                // 单元格内容写入
                $sheet->setCellValue($dataCol . $row, $item['imei']);$dataCol++;
                $sheet->setCellValue($dataCol . $row, $item['mac_id']);$dataCol++;
                $sheet->setCellValue($dataCol . $row, $item['online_ch']);$dataCol++;
                $sheet->setCellValue($dataCol . $row, $item['apk']);$dataCol++;
                $sheet->setCellValue($dataCol . $row, date("Y-m-d H:i:s",$item['install_time']));$dataCol++;
                $sheet->setCellValue($dataCol . $row, date("Y-m-d H:i:s",$item['last_time']));$dataCol++;

                $row++;
            }
        }
        $name = 'device_'.date('YmdHi');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        //删除清空：
        $spreadsheet->disconnectWorksheets();
        return jsonReturn(1, [], '导出成功');
    }

    /**
     * 设备通信日志列表
     * @param array $params
     * @return Json
     */
    public function deviceLogList(array $params): Json
    {
        if (!$params['imei']) {
            return jsonReturn(0, [], '参数错误');
        }
        $where[] = ['imei', '=', $params['imei']];
        //获取列表
        $data = DeviceLog::getList($where, $params['page'], $params['limit'], 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 出货事件
     * @param array $imeis
     * @return Json
     */
    public function shippingOrder(array $imeis): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $OrderNo = generateOrderNo();
            $Client->shippingOrder($imei, $OrderNo);
        }
        return jsonReturn(1, true);
    }

    /**
     * 电机出货长度事件
     * @param array $imeis
     * @param int $motor
     * @return Json
     */
    public function motorDeliveryLength(array $imeis, int $motor): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $res = $Client->motorDeliveryLength($imei, $motor);
            if ($res) {
                $data = ['motor' => $motor];
                Device::update($data, ['imei' => $imei]);
            }
        }
        return jsonReturn(1, true);
    }

    /**
     * 袋子余量传感器
     * @param array $imeis
     * @return Json
     */
    public function allowanceQuery(array $imeis): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $Client->allowanceQuery($imei);
        }
        return jsonReturn(1, true);
    }

    /**
     * 定时开关机事件
     * @param array $imeis
     * @param int $time_type
     * @param string $on_time
     * @param string $off_time
     * @return Json
     */
    public function timingSwitch(array $imeis, int $time_type, string $on_time, string $off_time): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $res = $Client->timingSwitch($imei, $time_type, $on_time, $off_time);
            if ($res) {
                $data = ['time_type' => $time_type, 'on_time' => $on_time, 'off_time' => $off_time,];
                Device::update($data, ['imei' => $imei]);
            }
        }
        return jsonReturn(1, true);
    }

    /**
     * 音量调整事件
     * @param array $imeis
     * @param int $volume
     * @return Json
     */
    public function volumeSet(array $imeis, int $volume): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $res = $Client->volumeSet($imei, $volume);
            if ($res) {
                $data = ['volume' => $volume];
                Device::update($data, ['imei' => $imei]);
            }
        }
        return jsonReturn(1, true);
    }

    /**
     * 设备重启事件
     * @param array $imeis
     * @return Json
     */
    public function deviceRestart(array $imeis): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $Client->deviceRestart($imei);
        }
        return jsonReturn(1, true);
    }

    /**
     * 设备日志开关
     * @param array $imeis
     * @param int $log_cat
     * @return Json
     */
    public function deviceLogCat(array $imeis, int $log_cat): Json
    {
        $Client = DeviceClient::getInstance();
        foreach ($imeis as $imei) {
            //下发指令
            $res = $Client->deviceLogCat($imei, $log_cat);
            if ($res) {
                $data = ['log_cat' => $log_cat];
                Device::update($data, ['imei' => $imei]);
            }
        }
        return jsonReturn(1, true);
    }


}
